package com.wuyan.wurpc.server.tcp;

import com.wuyan.wurpc.protocol.ProtocolConstant;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;
import lombok.extern.slf4j.Slf4j;

/**
 * 装饰者模式(使用recordParser对原有的buffer处理能力进行增强)
 */
@Slf4j
public class TcpBufferHandlerWrapper implements Handler<Buffer> {
    /**
     * 解析器，用于解决半包，粘包
     */
    private final RecordParser recordParser;

    public TcpBufferHandlerWrapper(Handler<Buffer> bufferHandler) {
        //初始化recordParser
        log.info("初始化recordParser");
        recordParser = initrecordParser(bufferHandler);
    }

    @Override
    public void handle(Buffer buffer) {
        recordParser.handle(buffer);
    }
    private RecordParser initrecordParser(Handler<Buffer> bufferHandler) {
        //构造parser
        RecordParser parser = RecordParser.newFixed(ProtocolConstant.MESSAGE_HEADER_LENGTH);
        parser.setOutput(new Handler<Buffer>() {
            //初始化
            int size = -1;
            //一次完整的读取(头+体)
            Buffer resultBuffer = Buffer.buffer();
            @Override
            public void handle(Buffer buffer) {
                // 1. 每次循环，首先读取消息头
                if(-1 == size){
                    System.out.println("size==-1时，读取消息长度前size = "+size+" parser = "+ parser);
                    //读取消息体长度
                    size = buffer.getInt(13);
                    parser.fixedSizeMode(size);
                    System.out.println("读取消息长度之后：--------------------------");
                    log.info("size = {}, parser = {}", size, parser);
                    resultBuffer.appendBuffer(buffer);
                    log.info("此时resultBuffer = {}", resultBuffer);
                }else{
                    //写入体信息得到结果
                    resultBuffer.appendBuffer(buffer);
                    //已拼接完整buffer，执行处理
                    bufferHandler.handle(resultBuffer);
                    log.info("已拼接完成：resultBuffer = {}", resultBuffer);
                    //重置一轮
                    parser.fixedSizeMode(ProtocolConstant.MESSAGE_HEADER_LENGTH);
                    size = -1;
                    resultBuffer = Buffer.buffer();
                    log.info("完成重置resultBuffer = {}， parser = {}", resultBuffer,parser);
                }
            }
        });
        

        return parser;
    }





}
